package com.zhb86.kuaipai.ui.home;


import android.os.Bundle;
import android.util.SparseArray;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.superyee.commonlib.ui.BaseFragment;
import com.superyee.commonlib.videoplayer.cache.PreloadManager;
import com.zhb86.kuaipai.R;
import com.zhb86.kuaipai.bean.VideoBean;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * 首页推荐
 */
public class FRecommend extends BaseFragment {


    public FRecommend() {
        // Required empty public constructor
    }

    private ViewPager2 mViewPager;
    private PreloadManager mPreloadManager;
    private int mPlayingPosition = -1;
    /**
     * VerticalViewPager是否反向滑动
     */
    private boolean mIsReverseScroll;
    private ViewPagerAdapter mAdapter;
    ViewPager2.OnPageChangeCallback mViewPagerCallback;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_recommend;
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        mViewPager = view.findViewById(R.id.viewPager);
        mPreloadManager = PreloadManager.getInstance(baseActivity);
        mAdapter = new ViewPagerAdapter(this, null);
        mViewPager.setAdapter(mAdapter);
        mViewPager.setOffscreenPageLimit(1);
        initViewPagerCallback();
        mViewPager.registerOnPageChangeCallback(mViewPagerCallback);
        mViewPager.postDelayed(new Runnable() {
            @Override
            public void run() {
                List<VideoBean> list = VideoBean.getTikTokVideoList(baseActivity);
                mAdapter.setNewData(list);
            }
        }, 500);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (getParentFragment() == null) {
            return;
        }
        if (isHidden() || !getUserVisibleHint() || getParentFragment().isHidden() || !getParentFragment().getUserVisibleHint()) {
            return;
        }
        startPlay();
    }

    private void startPlay() {
        int currentPos = mViewPager.getCurrentItem();
        if (currentPos < 0) {
            return;
        }
        FVideoPlay videoFragment = mAdapter.getItemFragment(currentPos);
        if (videoFragment != null) {
            videoFragment.startPlay();
            mPlayingPosition = currentPos;
        }
    }


//    @Override
//    public void onPause() {
//        super.onPause();
//        FVideoPlay videoPlay = mAdapter.getItemFragment(mViewPager.getCurrentItem());
//        if (videoPlay != null) {
//            videoPlay.pause();
//        }
//    }


    @Override
    public void initData() {

    }


    @Override
    protected void addListener() {

    }

    @Override
    protected void removeListener() {
        if (mViewPagerCallback != null)
            mViewPager.unregisterOnPageChangeCallback(mViewPagerCallback);
    }

    @Override
    public void onReceiverNotify(int action, Object obj, int statusCode) {

    }


    private void initViewPagerCallback() {
        mViewPagerCallback = new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels);
                mIsReverseScroll = position < mPlayingPosition;
            }

            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                if (position == mPlayingPosition) return;
                startPlay();
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                super.onPageScrollStateChanged(state);
                if (state == ViewPager2.SCROLL_STATE_IDLE) {
                    mPreloadManager.resumePreload(mPlayingPosition, mIsReverseScroll);
                } else {
                    mPreloadManager.pausePreload(mPlayingPosition, mIsReverseScroll);
                }
            }
        };
    }

    static class ViewPagerAdapter extends FragmentStateAdapter {

        public ViewPagerAdapter(@NonNull Fragment fragment, List<VideoBean> videoList) {
            super(fragment);
            this.videoList = videoList;
        }

        private List<VideoBean> videoList;
        SparseArray<WeakReference<FVideoPlay>> fragmentsArray = new SparseArray<>();

        public void setNewData(List<VideoBean> data) {
            if (videoList == null) {
                videoList = new ArrayList<>();
            }
            videoList.clear();
            if (data != null) {
                videoList.addAll(data);
            }
            notifyDataSetChanged();
        }

        @NonNull
        @Override
        public Fragment createFragment(int position) {
            WeakReference<FVideoPlay> reference = fragmentsArray.get(position);
            if (reference == null || reference.get() == null) {
                FVideoPlay videoFragment = FVideoPlay.newInstance(videoList.get(position), position, true);
                fragmentsArray.put(position, new WeakReference(videoFragment));
                return videoFragment;
            }
            return reference.get();
        }

        public FVideoPlay getItemFragment(int position) {
            return fragmentsArray == null ? null : fragmentsArray.get(position) == null ? null : fragmentsArray.get(position).get();
        }

        @Override
        public int getItemCount() {
            return videoList == null ? 0 : videoList.size();
        }
    }

}
